<template>
  <div class="applicant-form cute-form">
    <n-form
      ref="formRef"
      :model="formValue"
      :rules="rules"
      label-placement="top"
      require-mark-placement="right-hanging"
      size="medium"
      :show-feedback="true"
      :show-label="true"
    >
      <!-- 职位信息卡片 -->
      <n-card class="job-info-card section-card" title="职位信息">
        <div class="job-content">
          <div class="job-item">
            <span class="label">职位名称：</span>
            <span class="value">{{ resData.title }}</span>
          </div>
          <div class="job-item">
            <span class="label">职位描述：</span>
            <span class="value">{{ resData.description }}</span>
          </div>
        </div>
      </n-card>

      <p class="form-tip">
        <n-icon><InfoCircleOutlined /></n-icon>
        带 <span class="required">*</span> 为必填项
      </p>

      <!-- 基本信息区块 -->
      <n-card class="section-card" title="基本信息">
        <n-grid :cols="isMobile ? 1 : 2" :x-gap="24" responsive="screen">
          <n-grid-item>
            <n-form-item label="姓名" path="name" required>
              <n-input v-model:value="formValue.name" placeholder="请输入您的真实姓名" />
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="昵称" path="nickname">
              <n-input v-model:value="formValue.nickname" placeholder="请输入您的昵称（选填）" />
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-grid :cols="isMobile ? 1 : 2" :x-gap="24" responsive="screen">
          <n-grid-item>
            <n-form-item label="手机号码" path="phone" required>
              <n-input v-model:value="formValue.phone" placeholder="请输入您的手机号码" />
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="微信" path="wechat">
              <n-input v-model:value="formValue.wechat" placeholder="请输入您的微信号（选填）" />
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-grid :cols="isMobile ? 1 : 3" :x-gap="24" responsive="screen">
          <n-grid-item>
            <n-form-item label="性别" path="gender" required>
              <n-radio-group v-model:value="formValue.gender">
                <n-space>
                  <n-radio value="male" disabled>男</n-radio>
                  <n-radio value="female">女</n-radio>
                  <n-radio value="other" disabled>其他</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="年龄" path="age">
              <n-input-number v-model:value="formValue.age" :min="16" :max="100" placeholder="请输入您的年龄" />
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="体重(kg)" path="weight" required>
              <n-input-number v-model:value="formValue.weight" :min="30" :max="200" placeholder="请输入您的体重" />
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-form-item label="学历" path="education">
          <n-select v-model:value="formValue.education" :options="educationOptions" placeholder="请选择您的最高学历" />
        </n-form-item>
      </n-card>

      <!-- 照片上传区块 -->
      <n-card class="section-card photo-upload-card" title="个人照片">
        <n-form-item path="photos" required>
          <n-upload
            ref="uploadRef"
            list-type="image-card"
            :max="5"
            :default-upload="false"
            @before-upload="handleBeforeUpload"
            @change="handlePhotoChange"
            accept="image/jpeg,image/png,image/jpg,image/gif"
            :show-file-list="true"
            :file-list="formValue.photos"
          >
            <div class="upload-trigger">
              <n-icon size="24"><PlusOutlined /></n-icon>
              <p>{{ uploadingPhotos ? '上传中...' : '上传照片' }}</p>
            </div>
          </n-upload>
          <div class="form-tip">请上传2-5张个人照片，支持jpg、png、jpeg格式，每张不超过5MB</div>
        </n-form-item>
      </n-card>

      <!-- 个人特长区块 -->
      <n-card class="section-card" title="个人特长与兴趣">
        <n-form-item label="兴趣爱好" path="hobbies">
          <n-input
            v-model:value="formValue.hobbies"
            type="textarea"
            placeholder="请描述您的兴趣爱好（选填）"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </n-form-item>

        <n-form-item label="才艺展示" path="specialSkills">
          <n-input
            v-model:value="formValue.specialSkills"
            type="textarea"
            placeholder="请描述您的特长或才艺（选填）"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </n-form-item>

        <n-form-item label="自我介绍" path="selfIntroduction">
          <n-input
            v-model:value="formValue.selfIntroduction"
            type="textarea"
            placeholder="请进行自我介绍（选填）"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </n-form-item>
      </n-card>

      <!-- 工作偏好区块 -->
      <n-card class="section-card" title="工作偏好">
        <n-grid :cols="isMobile ? 1 : 2" :x-gap="24" responsive="screen">
          <n-grid-item>
            <n-form-item label="可否饮酒" path="canDrink" required>
              <n-radio-group v-model:value="formValue.canDrink">
                <n-space>
                  <n-radio v-for="option in yesNoOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="能否配合店内安排的直播宣传" path="canLivestream" required>
              <n-radio-group v-model:value="formValue.canLivestream">
                <n-space>
                  <n-radio v-for="option in yesNoOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-grid :cols="isMobile ? 1 : 2" :x-gap="24" responsive="screen">
          <n-grid-item>
            <n-form-item label="是否接受夜间加班(有补贴)" path="acceptNightShift" required>
              <n-radio-group v-model:value="formValue.acceptNightShift">
                <n-space>
                  <n-radio v-for="option in yesNoOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item label="期望工作时间" path="preferredShift" required>
              <n-radio-group v-model:value="formValue.preferredShift">
                <n-space>
                  <n-radio v-for="option in shiftOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-form-item label="每周空闲时间" path="weeklyAvailability" required>
          <n-input
            v-model:value="formValue.weeklyAvailability"
            type="textarea"
            placeholder="请描述您每周的空闲时间，例如：周一下午2点-5点，周末全天等"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </n-form-item>

        <n-form-item label="桌游与Switch熟悉程度" path="gameExperience" required>
          <n-select
            v-model:value="formValue.gameExperience"
            :options="gameExperienceOptions"
            placeholder="请选择您对桌游与Switch的熟悉程度"
          />
        </n-form-item>
      </n-card>

      <!-- 工作经历区块 -->
      <n-card class="section-card" title="工作经历">
        <span style="color: #888; font-size: 12px;">没有工作经历可以不填</span>
        <div v-for="(exp, index) in formValue.workExperience" :key="index" class="work-experience">
          <n-form-item class="work-experience-form-item">
              <n-card :bordered="true" size="small" class="experience-card">
                <template #header>
                  <div class="work-experience-header">
                    <span>工作经历 #{{ index + 1 }}</span>
                    <div class="work-experience-actions">
                      <n-button
                        circle
                        size="small"
                        type="error"
                        v-if="formValue.workExperience.length > 1"
                        @click="confirmDelete(index)"
                      >
                        <template #icon>
                          <n-icon><CloseOutlined /></n-icon>
                        </template>
                      </n-button>
                    </div>
                  </div>
                </template>

                <n-form-item :path="`workExperience[${index}].startDate`" label="开始时间">
                  <n-date-picker
                    v-model:value="exp.startDate"
                    type="date"
                    clearable
                    :locale="dateLocale"
                    :date-locale="dateZhCN"
                    style="width: 100%"
                  />
                </n-form-item>

                <n-form-item :path="`workExperience[${index}].endDate`" label="结束时间">
                  <n-date-picker
                    v-model:value="exp.endDate"
                    type="date"
                    clearable
                    :locale="dateLocale"
                    :date-locale="dateZhCN"
                    style="width: 100%"
                  />
                </n-form-item>

                <n-form-item :path="`workExperience[${index}].company`" label="工作单位">
                  <n-input v-model:value="exp.company" placeholder="请输入工作单位" />
                </n-form-item>

                <n-form-item :path="`workExperience[${index}].position`" label="职位">
                  <n-input v-model:value="exp.position" placeholder="请输入职位" />
                </n-form-item>

                <n-form-item :path="`workExperience[${index}].reasonForLeaving`" label="离职原因">
                  <n-input
                    v-model:value="exp.reasonForLeaving"
                    type="textarea"
                    placeholder="请输入离职原因"
                    :autosize="{ minRows: 2, maxRows: 3 }"
                  />
                </n-form-item>
              </n-card>
          </n-form-item>
        </div>
        <div class="add-work-experience">
          <n-button type="primary" @click="addWorkExperience" class="add-work-experience-btn" ghost>
            <template #icon>
              <n-icon><PlusOutlined /></n-icon>
            </template>
            添加工作经历
          </n-button>
        </div>
      </n-card>

      <div class="form-actions">
        <n-button type="primary" @click="handleSubmit" :loading="submitting" size="large" round> 提交简历 </n-button>
      </div>
    </n-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { useMessage, useDialog, zhCN, dateZhCN } from 'naive-ui';
import { upload } from 'qiniu-js';
import { PlusOutlined, CloseOutlined, InfoCircleOutlined } from '@vicons/antd';
import applicantApi from '../api/applicant';

const message = useMessage();
const dialog = useDialog();
const formRef = ref(null);
const submitting = ref(false);
const uploadingPhotos = ref(false);
const windowWidth = ref(typeof window !== 'undefined' ? window.innerWidth : 1024);

// 日期选择器本地化配置
const dateLocale = dateZhCN;

// 计算属性判断是否为移动端
const isMobile = computed(() => windowWidth.value <= 768);

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', handleResize);
    document.title = '欢迎选择伍月～';
  }
});

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener('resize', handleResize);
  }
});

const props = defineProps({
  linkToken: {
    type: String,
    required: true,
  },
  resData: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(['submit-success']);

// 表单数据（添加默认值）
const formValue = reactive({
  name: '',
  nickname: '',
  gender: 'female',
  age: null,
  education: null,
  photos: [], // 存储上传组件的文件列表
  photoUrls: [], // 存储七牛云返回的图片URL
  message: '',
  phone: '', // 手机号码
  weight: null, // 体重
  wechat: '', // 微信联系方式
  hobbies: '', // 兴趣爱好
  specialSkills: '', // 才艺
  canDrink: 'yes', // 可否饮酒
  canLivestream: 'yes', // 能否配合直播
  acceptNightShift: 'yes', // 是否能接受夜班
  preferredShift: 'day', // 工作时间倾向
  weeklyAvailability: '', // 周一至周日空闲时间
  workExperience: [
    {
      // 工作经历
      startDate: null,
      endDate: null,
      company: '',
      position: '',
      reasonForLeaving: '',
    },
  ],
  gameExperience: 'familiar', // 桌游与switch熟悉程度
  selfIntroduction: '', // 自我介绍
});

// 学历选项
const educationOptions = [
  { label: '高中/中专', value: '高中/中专' },
  { label: '大专', value: '大专' },
  { label: '本科', value: '本科' },
  { label: '硕士', value: '硕士' },
  { label: '博士', value: '博士' },
  { label: '其他', value: '其他' },
];

// 时间选项
const shiftOptions = [
  { label: '早班（12:00-20:00）', value: 'day' },
  { label: '晚班（18:00-次日2:00）', value: 'night' },
];

// 是否选项
const yesNoOptions = [
  { label: '是', value: 'yes' },
  { label: '否', value: 'no' },
];

// 游戏熟悉度选项
const gameExperienceOptions = [
  { label: '完全不了解', value: 'none' },
  { label: '略有了解', value: 'basic' },
  { label: '比较熟悉', value: 'familiar' },
  { label: '非常熟悉', value: 'expert' },
];

// 表单验证规则
const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入姓名',
  },
  gender: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择性别',
  },
  photos: {
    required: true,
    trigger: ['change'],
    message: '请上传至少两张照片',
    validator: (rule, value) => {
      console.log('验证照片数组:', formValue.photoUrls);
      if (!Array.isArray(formValue.photoUrls)) {
        return new Error('请上传至少两张照片');
      }

      // 过滤出有效的URL
      const validUrls = formValue.photoUrls.filter((url) => url && typeof url === 'string');
      console.log('有效照片URL数量:', validUrls.length);

      if (validUrls.length <= 1) {
        return new Error('请上传至少两张张照片');
      }
      return true;
    },
  },
  phone: {
    required: true,
    trigger: ['blur', 'input'],
    validator: (rule, value) => {
      if (!value) {
        return new Error('请输入手机号码');
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        return new Error('请输入正确的手机号码');
      }
      return true;
    },
  },
  weight: {
    required: true,
    trigger: ['blur', 'change'],
    validator: (rule, value) => {
      if (!value && value !== 0) {
        return new Error('请输入体重');
      }
      if (value < 30 || value > 200) {
        return new Error('请输入合理的体重范围（30-200）');
      }
      return true;
    },
  },
  canDrink: {
    required: true,
    trigger: ['change'],
    message: '请选择是否可以饮酒',
  },
  canLivestream: {
    required: true,
    trigger: ['change'],
    message: '请选择是否能配合直播宣传',
  },
  acceptNightShift: {
    required: true,
    trigger: ['change'],
    message: '请选择是否能接受夜班',
  },
  preferredShift: {
    required: true,
    trigger: ['change'],
    message: '请选择期望的工作时间',
  },
  weeklyAvailability: {
    required: true,
    trigger: ['blur', 'input'],
    validator: (rule, value) => {
      if (!value || value.trim() === '') {
        return new Error('请填写每周空闲时间');
      }
      return true;
    },
  },
  gameExperience: {
    required: true,
    trigger: ['change'],
    message: '请选择游戏熟悉程度',
  },
};

// 上传照片到七牛云
const uploadToQiniu = async (file) => {
  try {
    console.log('开始获取上传凭证，文件:', file.name);
    const response = await applicantApi.getUploadToken('image');
    console.log('获取上传凭证响应:', response);

    // 检查响应格式
    if (!response || !response.success) {
      throw new Error('获取上传凭证失败: 响应格式错误');
    }

    // 从后端响应中获取token对象
    const { token, key, domain } = response.data.token;

    if (!token || !key || !domain) {
      throw new Error('获取上传凭证失败: 缺少必要参数');
    }

    console.log('获取上传凭证成功:', {
      token: token.substring(0, 10) + '...',
      key,
      domain,
    });

    return new Promise((resolve, reject) => {
      // 设置额外参数
      const putExtra = {
        fname: file.name,
        params: {},
        mimeType: null,
      };

      // 设置上传配置
      const config = {
        useCdnDomain: true,
        region: null, // 自动检测区域
        retryCount: 3,
      };

      console.log('开始上传文件到七牛云:', file.name);

      // 创建上传observable
      console.log(upload);
      const observable = upload(file, key, token, putExtra, config);

      // 创建上传订阅
      const subscription = observable.subscribe({
        next: (res) => {
          // 上传进度
          console.log('上传进度：', res.total.percent.toFixed(2) + '%');
        },
        error: (err) => {
          // 上传错误
          console.error('七牛云上传错误:', err);
          reject(err);
        },
        complete: (res) => {
          // 上传完成
          console.log('七牛云上传完成:', res);
          const url = `${domain}${key}`;
          console.log('构建的URL:', url);
          resolve(url);
        },
      });

      // 保存订阅对象，以便可以取消
      file._subscription = subscription;
    });
  } catch (error) {
    console.error('获取上传凭证或上传过程失败:', error);
    throw error;
  }
};

// 处理上传前的回调
const handleBeforeUpload = (data) => {
  console.log('准备上传文件:', data.file.name, data);
  // 这里可以做文件类型和大小的检查
  const isImage = /^image\/(jpeg|png|gif|jpg)$/i.test(data.file.type);
  const isLt5M = data.file.file.size / 1024 / 1024 < 5;

  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }

  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
    return false;
  }

  return true; // 返回 true 允许上传
};

// 处理照片上传 - 修改为选择后立即上传
const handlePhotoChange = async (options) => {
  const { file, fileList } = options;
  console.log('文件状态变化:', file.status, '文件名:', file.name, '文件列表长度:', fileList.length);

  // 更新文件列表
  formValue.photos = fileList;

  if (fileList.length > 5) {
    message.error('最多只能上传5张照片');
    formValue.photos = formValue.photos.slice(0, 5);
    return;
  }

  // 当文件被添加时，立即开始上传
  if (file.status === 'ready' || file.status === 'pending') {
    console.log('文件状态为ready/pending，开始上传');

    // 确保文件有效且未开始上传
    if (file.file && !file._uploading) {
      const currentFile = file;
      currentFile._uploading = true;
      uploadingPhotos.value = true;

      // 找到当前文件在列表中的索引
      const index = formValue.photos.findIndex((f) => f.id === currentFile.id);
      if (index > -1) {
        // 更新状态为上传中
        formValue.photos[index] = {
          ...formValue.photos[index],
          status: 'uploading',
        };
      }

      message.info(`开始上传: ${currentFile.name || '图片'}`);

      try {
        const url = await uploadToQiniu(currentFile.file);
        console.log('上传成功，URL:', url);

        // 再次查找索引，因为在异步操作过程中列表可能已经改变
        const updatedIndex = formValue.photos.findIndex((f) => f.id === currentFile.id);
        if (updatedIndex > -1) {
          formValue.photos[updatedIndex] = {
            ...formValue.photos[updatedIndex],
            status: 'finished',
            url,
            _uploading: false,
          };

          message.success(`${currentFile.name || '图片'} 上传成功`);
        }

        // 更新photoUrls
        formValue.photoUrls = formValue.photos.filter((f) => f.status === 'finished' && f.url).map((f) => f.url);

        console.log('当前照片URLs:', formValue.photoUrls);

        // 不要在这里手动触发验证，避免validateCallback错误
      } catch (error) {
        console.error('上传失败:', error);
        message.error(`${currentFile.name || '图片'} 上传失败，请重试: ${error.message || '未知错误'}`);

        // 更新文件状态为错误
        const errorIndex = formValue.photos.findIndex((f) => f.id === currentFile.id);
        if (errorIndex > -1) {
          formValue.photos[errorIndex] = {
            ...formValue.photos[errorIndex],
            status: 'error',
            _uploading: false,
          };
        }
      } finally {
        // 检查是否还有其他文件正在上传
        const stillUploading = formValue.photos.some((f) => f._uploading === true);
        if (!stillUploading) {
          uploadingPhotos.value = false;
        }
      }
    }
  } else if (file.status === 'removed') {
    // 处理照片移除
    // 如果文件正在上传，取消上传订阅
    if (file._subscription) {
      console.log('取消上传订阅:', file.name);
      file._subscription.unsubscribe();
    }

    formValue.photos = formValue.photos.filter((f) => f.id !== file.id);

    // 更新photoUrls
    formValue.photoUrls = formValue.photos.filter((f) => f.status === 'finished' && f.url).map((f) => f.url);

    console.log('更新后的照片URLs:', formValue.photoUrls);
    message.info(`已移除: ${file.name || '图片'}`);

    // 不要在这里手动触发验证，避免validateCallback错误
  }
};

// 提交表单
const handleSubmit = async (e) => {
  e.preventDefault();
  console.log('提交时的照片URLs:', formValue.photoUrls);

  if (uploadingPhotos.value) {
    message.warning('请等待照片上传完成后再提交');
    return;
  }

  // 检查照片是否已上传
  if (!Array.isArray(formValue.photoUrls) || formValue.photoUrls.length < 2) {
    message.error('请至少上传两张照片');
    // 滚动到photo-upload-card
    const photoUploadCard = document.querySelector('.photo-upload-card');
    if (photoUploadCard) {
      photoUploadCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
    return;
  }

  submitting.value = true;

  try {
    if (formRef.value) {
      // 使用try/catch来捕获验证错误
      try {
        await formRef.value.validate();
      } catch (errors) {
        console.log('表单验证失败:', errors);
        
        // 找到第一个错误的表单项
        if (errors && typeof errors === 'object') {
          const firstErrorField = Object.keys(errors)[0];
          const firstErrorMessage = errors[firstErrorField][0]?.message;
          
          // 显示错误信息
          if (firstErrorMessage) {
            message.error(firstErrorMessage);
          }
          
          // 滚动到第一个错误的表单项
          scrollToFirstError();
        }
        
        // 停止loading状态
        submitting.value = false;
        return; // 验证失败，不继续执行
      }
    }

    // 准备提交数据
    const submitData = {
      linkToken: props.linkToken,
      name: formValue.name,
      nickname: formValue.nickname,
      phone: formValue.phone,
      wechat: formValue.wechat,
      gender: formValue.gender,
      age: formValue.age,
      weight: formValue.weight,
      education: formValue.education,
      photos: formValue.photoUrls.filter((url) => url && typeof url === 'string'), // 确保只提交有效URL
      hobbies: formValue.hobbies,
      specialSkills: formValue.specialSkills,
      canDrink: formValue.canDrink,
      canLivestream: formValue.canLivestream,
      acceptNightShift: formValue.acceptNightShift,
      preferredShift: formValue.preferredShift,
      weeklyAvailability: formValue.weeklyAvailability,
      workExperience: formValue.workExperience.filter(
        (exp) => exp.company || exp.position || exp.startDate || exp.endDate || exp.reasonForLeaving
      ),
      gameExperience: formValue.gameExperience,
      selfIntroduction: formValue.selfIntroduction,
    };

    console.log('提交的数据:', submitData);

    // 确保照片数组不为空
    if (!submitData.photos.length) {
      message.error('请至少上传两张照片');
      submitting.value = false;
      return;
    }

    const response = await applicantApi.submitApplication(submitData);
    console.log('提交响应:', response);

    if (response && response.success) {
      message.success('简历提交成功！');
      emit('submit-success');
    } else {
      throw new Error(response?.message || '提交失败，请稍后重试');
    }
  } catch (error) {
    console.error('提交失败:', error);

    // 处理API错误
    if (error.response && error.response.data) {
      message.error(error.response.data.message || '提交失败，请稍后重试');
    } else {
      message.error(error.message || '提交失败，请稍后重试');
    }
  } finally {
    submitting.value = false;
  }
};

// 滚动到第一个错误的表单项
const scrollToFirstError = () => {
  // 使用setTimeout确保DOM已更新
  setTimeout(() => {
    // 查找所有带有错误反馈的表单项
    const errorItems = document.querySelectorAll('.n-form-item-feedback--error');
    
    if (errorItems && errorItems.length > 0) {
      // 找到第一个错误表单项的父元素（n-form-item），这样可以看到完整的表单项
      let target = errorItems[0];
      let parent = target.parentElement;
      
      // 往上查找直到找到n-form-item
      while (parent && !parent.classList.contains('n-form-item')) {
        parent = parent.parentElement;
      }
      
      // 如果找到了，滚动到这个元素
      if (parent) {
        parent.scrollIntoView({ behavior: 'smooth', block: 'center' });
      } else {
        // 如果没找到，滚动到错误消息本身
        target.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    }
  }, 200); // 给DOM有充分的时间更新
};

// 添加/删除工作经历
const addWorkExperience = () => {
  formValue.workExperience.push({
    startDate: null,
    endDate: null,
    company: '',
    position: '',
    reasonForLeaving: '',
  });
};

const removeWorkExperience = (index) => {
  formValue.workExperience.splice(index, 1);
};

// 确认删除工作经历
const confirmDelete = (index) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这条工作经历吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      removeWorkExperience(index);
      message.success('已删除工作经历');
    },
  });
};
</script>

<style scoped>
.applicant-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
}

.section-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.section-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.job-info-card {
  background-color: #fff5f8;
  border-left: 4px solid #ff85a2;
}

.job-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.job-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.job-item .label {
  font-weight: 500;
  margin-right: 8px;
  min-width: 80px;
}

.job-item .value {
  color: #666;
  flex: 1;
}

.form-tip {
  font-size: 12px;
  color: #888;
  margin: 8px 0 16px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.required {
  color: #ff4d4f;
  font-weight: bold;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.form-actions button {
  min-width: 180px;
  height: 46px;
  font-size: 16px;
  background-color: #ff85a2 !important;
  border-color: #ff85a2 !important;
}

.form-actions button:hover {
  background-color: #ff6b8e !important;
  border-color: #ff6b8e !important;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.upload-trigger p {
  margin-top: 8px;
  font-size: 12px;
}

.work-experience {
  width: 100%;
}

.experience-card {
  border: 1px solid #eee;
  transition: all 0.3s ease;
  width: 100%;
}

.experience-card:hover {
  border-color: #ff85a2;
}

.work-experience-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  width: 100%;
}

.work-experience-actions {
  display: flex;
  gap: 8px;
}

.add-work-experience {
  display: flex;
  justify-content: center;
  width: 100%;
}

.add-work-experience-btn {
  width: 100%;
  max-width: 200px;
  color: #fff !important;
  border-color: #ff85a2 !important;
  margin-bottom: 16px;
}

.add-work-experience-btn:hover {
  color: #fff !important;
  background-color: #ff85a2 !important;
}

/* 移动端适配样式 */
@media (max-width: 768px) {
  .applicant-form {
    padding: 10px 0;
  }

  .section-card {
    margin-bottom: 16px;
  }

  .job-item {
    flex-direction: column;
  }

  .job-item .label {
    margin-bottom: 4px;
    min-width: auto;
  }

  :deep(.n-form-item) {
    margin-bottom: 12px;
  }

  :deep(.n-form-item .n-form-item-label) {
    padding-bottom: 6px;
  }

  :deep(.n-radio-group) {
    flex-wrap: wrap;
  }

  :deep(.n-date-picker) {
    width: 100%;
  }

  :deep(.n-input-number) {
    width: 100%;
  }

  :deep(.n-card-header) {
    padding: 12px 16px;
  }

  :deep(.n-card__content) {
    padding: 12px 16px;
  }

  .form-actions button {
    min-width: 140px;
    height: 40px;
    font-size: 14px;
    width: 100%;
  }
}

/* 全局样式覆盖 */
:deep(.n-button--primary-type) {
  background-color: #ff85a2 !important;
  border-color: #ff85a2 !important;
}

:deep(.n-button--primary-type:hover) {
  background-color: #ff6b8e !important;
  border-color: #ff6b8e !important;
}

:deep(.n-radio-input.n-radio-input--checked) {
  background-color: #ff85a2 !important;
  border-color: #ff85a2 !important;
}

:deep(.n-checkbox-box.n-checkbox-box--checked) {
  background-color: #ff85a2 !important;
  border-color: #ff85a2 !important;
}

:deep(.n-input:hover .n-input__border) {
  border-color: #ff85a2 !important;
}

:deep(.n-input:focus .n-input__border) {
  border-color: #ff85a2 !important;
}

:deep(.n-input.n-input--focus .n-input__border) {
  border-color: #ff85a2 !important;
  box-shadow: 0 0 0 2px rgba(255, 133, 162, 0.2) !important;
}
</style>
